import { DirectiveOptions } from 'vue'
import Hammer from 'hammerjs'

let index = 0
const hammerArr = {} as any
const vTouch: DirectiveOptions = {
  bind (el, binding) {
    let hammertime
    if (!el.dataset.hammmer) {
      hammertime = new Hammer(el)
      const hammerId = `hammer${index++}`
      el.dataset.hammer = hammerId
      hammerArr[hammerId] = hammertime
    }
    for (let eventName in binding.value) {
      hammertime.on(eventName.toLowerCase(), binding.value[eventName])
    }
  },
  unbind (el, binding) {
    const hammerId = el.dataset.hammer
    if (!hammerId) {
      return
    }
    const hammertime = hammerArr[hammerId]
    if (!hammertime) {
      return
    }
    console.log('unbind', hammerId)
    for (let eventName in binding.value) {
      hammertime.off(eventName.toLowerCase(), binding.value[eventName])
    }
    delete hammerArr[hammerId]
    el.dataset.hammer = ''
  },
}

export default vTouch
